package com.ciwong.epaper.modules.dictation.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.modules.dictation.adpter.DictationRedoAdapter;
import com.ciwong.epaper.modules.dictation.bean.DictationAnswerInfo;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.SubmitResult;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.UnitSpeechControler;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.QQShareListener;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.Base64Utils;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.SubmitSuccessfulResultPage;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.tauth.UiError;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by keepon on 2018/7/13.
 */
public class DictationRedoAndResultActivity extends BaseActivity implements View.OnClickListener, DictationRedoAdapter.OnRedoWordListener {
    private static final int ANSWER_SUBMIT = 10000;
    private static final int MSG_NET_SPEED = 10001;
    public Button commit_homework_btn, retry_submit_bt;//交作业按钮   重新提交按钮
    private LinearLayout submiting;//结果容器  提交中   提交失败
    private RelativeLayout result_contail, submit_fail;
    private ViewGroup submit_result_lay;//提交成功页面
    private SubmitSuccessfulResultPage score_result_page;//结果控件
    private ListView mRedoListView;
    private ImageView wechat, wechatFriend, qq, qqFriend;//分享
    private TextView tx_upload_progress;
    private SeekBar submit_seek_bar_make_score;//提交进度
    private Button btn_return_last_page;
    private ImageView iv_close_page;

    private DictationRedoAdapter mDictationRedoAdapter;
    private Answer mAnswer;
    private WorkContents mWorkContents;
    private boolean mIsSubmited = false, mIsHasSubmited = false;// 是否提交作业成功  是否已经提交过作业

    //本地作业列表
    private List<MyWork> mLocalWorkList;

    //截止时间
    private long effectiveDate = -1;

    private long nowTime = 0;

    //查看类型
    private int ShowScoreMode;
    private long startTime;
    private long returnWorkLong;
    private EApplication application;
    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;
    ArrayList<DictationAnswerInfo> mListenWordAnswerInfos;
    private ArrayList<WordDetail> mWordDetailList;
    ArrayList<WorkAnswers<DictationAnswerInfo>> mSubmitAnswers;
    private int submint_timer;
    private float mTotalScore = 100;
    private int mWorkLong;
    private double mActualScore;
    private String mUuid;
    private String mVersionId, mWorkId, mDoWorkId, mParentVersionId, mTitleText;
    private int mPosition;
    private DownLoadInfo mDownLoadInfo;
    private Module mModule;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_NET_SPEED:
                    try {
                        int speed = (int) msg.obj;
                        int remainSecods = 2;
                        tx_upload_progress.setVisibility(View.VISIBLE);
                        tx_upload_progress.setText(ListenSpeakUtil.formatNetSpeed(DictationRedoAndResultActivity.this, speed, remainSecods, true));
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                    break;
                case ANSWER_SUBMIT:
                    submint_timer++;
                    if (submint_timer < 30) {
                        if (submint_timer <= 4) {
                            submit_seek_bar_make_score.setProgress(submint_timer);
                        }
                        mHandler.sendEmptyMessageDelayed(ANSWER_SUBMIT, 1000);
                    } else {
                        //过了20S,强制让用户重试
                        result_contail.setVisibility(View.GONE);
                        submiting.setVisibility(View.GONE);
                        submit_fail.setVisibility(View.VISIBLE);
                        submit_seek_bar_make_score.setProgress(0);
                    }

                    break;
            }
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_dication_redo_and_result;
    }

    @Override
    protected void findViews() {
        mRedoListView = findViewById(R.id.redo_word_result_lv);
        commit_homework_btn = findViewById(R.id.commit_homework_btn);
        retry_submit_bt = findViewById(R.id.retry_submit_bt);
        result_contail = findViewById(R.id.result_contail);
        submiting = findViewById(R.id.submiting);
        submit_fail = findViewById(R.id.submit_fail);
        submit_seek_bar_make_score = findViewById(R.id.submit_seek_bar_make_score);
        submit_result_lay = findViewById(R.id.submit_result_lay);
        score_result_page = findViewById(R.id.score_result_page);

        wechat = score_result_page.findViewById(R.id.share_weixin);
        wechatFriend = score_result_page.findViewById(R.id.share_weixin_friend);
        qq = score_result_page.findViewById(R.id.share_qq);
        qqFriend = score_result_page.findViewById(R.id.share_qq_space);
        tx_upload_progress = findViewById(R.id.tx_upload_progress);

        btn_return_last_page = score_result_page.findViewById(R.id.btn_return_last_page);
        iv_close_page = score_result_page.findViewById(R.id.iv_close_page);
        mRedoListView.setBackgroundResource(R.mipmap.bg_diactaion_redo);
        submit_seek_bar_make_score.setMax(5);
    }

    @Override
    protected void initEvent() {
        application = (EApplication) getApplication();
        if (application != null) {
            //服务是否过期
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContents != null && mWorkContents.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        btn_return_last_page.setOnClickListener(this);
        iv_close_page.setOnClickListener(this);
        commit_homework_btn.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {//提交作业
                try {
                    if (EConstants.IS_YOUKE) {
                        EConstants.WORD_IS_YOUKE_LOGIN = true;
                        NewLoginDialog newLoginDialog = new NewLoginDialog(DictationRedoAndResultActivity.this);
                        newLoginDialog.showLoginDialog();
                    } else {
                        if (NetworkUtils.isOnline()) {
                            mActualScore = getAvgScore();
                            submit();
                        } else {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                        }
                    }

                } catch (Exception e) {
                    e.getStackTrace();
                }


            }
        });

        retry_submit_bt.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {//重新提交
                try {
                    if (EConstants.IS_YOUKE) {
                        EConstants.WORD_IS_YOUKE_LOGIN = true;
                        NewLoginDialog newLoginDialog = new NewLoginDialog(DictationRedoAndResultActivity.this);
                        newLoginDialog.showLoginDialog();
                    } else {
                        if (NetworkUtils.isOnline()) {
                            submit_fail.setVisibility(View.GONE);
                            mActualScore = getAvgScore();
                            submit();
                        } else {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                        }
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });

        score_result_page.setOnCheckDetailListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(DictationRedoAndResultActivity.this, mAnswer.getContentId() + "", 0);
                if (!orNotWatchDetails)
                    return;
                if (serviceExpired) {
                    // 直接跳转到新的学习记录页面
                    jumpToStudyRecordH5();
                } else {
                    setBuyServiceDialog();
                }
            }
        });
        score_result_page.setOnCheckTipsListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(DictationRedoAndResultActivity.this, mAnswer.getContentId() + "", 0);
                if (!orNotWatchDetails)
                    return;
                if (serviceExpired) {
                    // 直接跳转到新的学习记录页面
                    jumpToStudyRecordH5();
                } else {
                    setBuyServiceDialog();
                }
            }
        });

        wechat.setOnClickListener(new ViewOnClickListener() {//微信分享
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(1);
            }
        });
        wechatFriend.setOnClickListener(new ViewOnClickListener() {//
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(2);
            }

        });

        qq.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                qqShare("QQ");
            }
        });

        qqFriend.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                qqShare("QZone");
            }
        });

        setGoBackListener(goBackListener);
    }

    /**
     * 直接跳转到新的学习记录页面
     */
    private void jumpToStudyRecordH5() {
        try {
            //直接跳转到新的学习记录页面
            String url = EpaperConstant.URL_H5_DICATION + "pageType=1";
            StringBuffer sb = new StringBuffer(url);
            sb.append("&clientId=");
            sb.append(EConstants.CLIENT_ID);
            long useeId = getUserInfoBase().getUserId();
            sb.append("&userId=");
            sb.append(useeId);
            sb.append("&brandId=");
            sb.append(EApplication.BRAND_ID);
            sb.append("&versionId=");
            sb.append("0".equals(mVersionId) ? mParentVersionId : mVersionId);
            sb.append("&parentVersionId=");
            sb.append(mParentVersionId);
            sb.append("&doWorkId=");
            sb.append(mDoWorkId);
            String title;
            try {
                title = java.net.URLEncoder.encode(mTitleText, "UTF-8");
            } catch (Exception e) {
                title = "";
            }
            title = title.replace("+", "%20");
            sb.append("&title=");
            sb.append(title);
            MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, DictationRedoAndResultActivity.this, R.string.go_back, -1, sb.toString(), mTitleText, 0);

        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(DictationRedoAndResultActivity.this);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    if (mAnswer != null && mAnswer.getWorkType() > 0) {
                        int serviceId = 0;
                        try {
                            serviceId = mAnswer.getWorkType();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //购买服务包
                        MeJumpManager.jumpBuyService(DictationRedoAndResultActivity.this, R.string.go_back, serviceId, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    } else {
                        //拓展服务
                        MeJumpManager.jumpToResourseCenterH5Activity(DictationRedoAndResultActivity.this, R.string.go_back, getResources().getString(R.string.resource_center));
                    }
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    /**
     * "QQ"代表分享给QQ好友，"QZone"代表分享到QQ空间
     *
     * @param qq
     */

    private void qqShare(String qq) {
        try {
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            shareMsgObj.setLocalImgUrl(FileUtil.getShareWordIconLocalPath(getApplicationContext()));
            shareMsgObj.setUrl(getShareBase64Url());
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(mActualScore));
            String shareContent = getString(R.string.str_share_content, score);
            if (qq.equals("QQ")) {
                shareMsgObj.setMsgDesription(shareContent);
                shareMsgObj.setMsgTitle(mTitleText);
                QQShareHelper.getInstance().shareToQQ(DictationRedoAndResultActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(mDoWorkId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {
                    }

                    @Override
                    public boolean onQQShareCancel() {
                        return false;
                    }
                });
            } else if (qq.equals("QZone")) {
                shareMsgObj.setMsgTitle(shareContent);
                shareMsgObj.setImg_url(FileUtil.getShareWordIconLocalPath(getApplicationContext()));
                QQShareHelper.getInstance().shareToQZone(DictationRedoAndResultActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(mDoWorkId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {

                    }

                    @Override
                    public boolean onQQShareCancel() {

                        return false;
                    }
                });
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        try {
            WxShareHelper.getInstance().initWxShare(DictationRedoAndResultActivity
                    .this, new WxShareListener() {
                @Override
                public void onWxShareing(String str) {

                    Log.d("sharetest", "##########onWxShareing######" + str);
                }

                @Override
                public void onWxShareSucc(String var) {
                    shareAddPointType(mDoWorkId, AddPointTypes.SHERE_SCORE);
                    Log.d("sharetest", "##########onWxShareSucc######" + var);
                }

                @Override
                public void onWxShareFailure(int var, String var1) {
                    Log.d("sharetest", "##########onWxShareFailure######" + var1);
                }

                @Override
                public boolean onWxShareCancel() {
                    Log.d("sharetest", "##########onWxShareCancel######");
                    return false;
                }
            });
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setWxType(wxType);
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.word_share_icon);
            shareMsgObj.setThunbBmp(bmp);

            shareMsgObj.setUrl(getShareBase64Url());
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(mActualScore));
            String shareContent = getString(R.string.str_share_content, score);
            if (wxType == 1) {
                shareMsgObj.setMsgDesription(shareContent);
                shareMsgObj.setMsgTitle(mTitleText);
            } else if (wxType == 2) {
                shareMsgObj.setMsgTitle(shareContent);
            }
            WxShareHelper.getInstance().sendReq(shareMsgObj);
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    private void shareAddPointType(String doWorkId, String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, doWorkId);
    }

    @Override
    public void onBackPressed() {
        goBackListener.goBack();
    }

    GoBackListener goBackListener = new GoBackListener() {
        @Override
        public void goBack() {
            if (mIsHasSubmited) {
                saveDoWorkRecord(mListenWordAnswerInfos);
                showConfirmEndDialog();
            } else if (mIsSubmited) {
                saveDoWorkRecord(null);
                FileUtils.delete(ESystem.getAnswersUuidPath(mUuid));
                CWSys.setSharedInt(getSaveTime(), 0);
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                finish();
            } else {
                showDailog();
                saveDoWorkRecord(mListenWordAnswerInfos);

            }
            UnitSpeechControler.readCount = 0;
        }
    };

    @Override
    protected void init() {
        isSupportQQAndQQZone();
        setValideSource(false);
        setBackImg(R.mipmap.icon_x_exit);
        new Timer().schedule(netSpeedTask, 1000, 600); // 1s后启动任务，每2s执行一次
    }

    @Override
    protected void loadData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }

        try {
            Bundle bundle = intent.getBundleExtra(IntentFlag.INTENT_FLAG_OBJ);
            mSubmitAnswers = new ArrayList<>();
            if (bundle != null) {
                mListenWordAnswerInfos = (ArrayList<DictationAnswerInfo>) bundle.getSerializable(IntentFlag.INTENT_FLAG_USERANSWERLIST);
                mWordDetailList = (ArrayList<WordDetail>) bundle.getSerializable(IntentFlag.INTENT_FLAG_WORDSLIST);
                mDownLoadInfo = (DownLoadInfo) bundle.getSerializable(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            }
            mAnswer = (Answer) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);
            mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_MODULE);
            mPosition = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
            mTitleText = intent.getStringExtra(IntentFlag.INTENT_FLAG_TITLE);
            mWorkContents = (WorkContents) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENTS);
            effectiveDate = getIntent().getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, -1);
            if (mAnswer != null) {
                mVersionId = mAnswer.getVersionId();
                mWorkId = mAnswer.getWorkId();
                mParentVersionId = mAnswer.getParentVersionId();
                mTitleText = mAnswer.getResourceName();
                mWorkLong = mAnswer.getWorkLong();
            }

            setTitleText(mTitleText);

            mUuid = intent.getStringExtra(IntentFlag.INTENT_FLAG_UUID);


            if (CWSys.getSharedBoolean(getSubmitStateKey(), false)) {//已经提交过 直接显示提交失败页面
                result_contail.setVisibility(View.GONE);
                submiting.setVisibility(View.GONE);
                submit_fail.setVisibility(View.VISIBLE);
            } else {
                mDictationRedoAdapter = new DictationRedoAdapter(DictationRedoAndResultActivity.this, mListenWordAnswerInfos, serviceExpired);
                mRedoListView.setAdapter(mDictationRedoAdapter);
                mDictationRedoAdapter.setOnRedoWordListener(this);
            }
            //获取保存本地的开始时间
            startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, mPosition, mWorkId), 0);
            if (startTime == 0) {
                startTime = mDownLoadInfo.getStartTime();
            }


        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_return_last_page || id == R.id.iv_close_page) {
            Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
            //        作业状态(1:已提交 2:退回 4:已批改完成 8:无法识别答题卡 16:等待批改)
            int workStatus = 1;//听说模考评分中传16，其他默认传1.
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, workStatus);//
            intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, mActualScore);
            sendBroadcast(intent);
            finish();

        }
    }

    public void isSupportQQAndQQZone() {
        if (EConstants.QQ_APP_ID.equals("") || null == EConstants.QQ_APP_ID) {
            qq.setImageResource(R.mipmap.share_qq_unstalled);
            qqFriend.setImageResource(R.mipmap.share_qq_space_unstalled);
            qq.setEnabled(false);
            qqFriend.setEnabled(false);
        }

    }

    public void submit() {//提交作业
        submint_timer = 0;//计时归0
        mHandler.sendEmptyMessage(ANSWER_SUBMIT);//发动计时器
        mIsHasSubmited = true;
        saveSubmitState(true);//提交过作业


        result_contail.setVisibility(View.GONE);
        submiting.setVisibility(View.VISIBLE);

        submitJson();
    }

    public void submitJson() {//提交答案数据
        try {
            if (mAnswer == null) {
                return;
            }
            if (submit_fail.getVisibility() == View.VISIBLE) {//如果失败页面显示  则不提交答案
                return;
            }

            mAnswer.setActualScore((float) getAvgScore());//实际得分
            UserInfoBase userInfoBase = getUserInfoBase();
            if (userInfoBase != null) {
                mAnswer.setUserName(userInfoBase.getRealName());
                mAnswer.setUserId(userInfoBase.getUserId());
            }

            String uuid = CWSys.getSharedString(RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo, mModule, mPosition, mWorkId, 0), null);
            Log.d(TAG, "#######submit() 提交作业 uuid#########" + uuid);
            if (null != uuid) {
                mAnswer.setSessionId(uuid);
                //有可能提交成功清除uuid后再结果页面停留或者用清理软件销毁当前页面，重新生成页面后 uuid 没有
            } else {
                //清除做作业记录  相关缓存
                CWSys.setSharedInt(getSaveTime(), 0);
                saveDoWorkRecord(null);
                finish();
                return;
            }
            //组装WorkAnswers<DictationAnswerInfo>格式的答案
            for (DictationAnswerInfo listenWordAnswerInfo : mListenWordAnswerInfos) {
                WorkAnswers<DictationAnswerInfo> listenWordAnswerInfoWorkAnswers = new WorkAnswers<>();
                ArrayList<DictationAnswerInfo> listenWordAnswerInfos = new ArrayList<>();
                listenWordAnswerInfos.add(listenWordAnswerInfo);
                listenWordAnswerInfoWorkAnswers.setAnswers(listenWordAnswerInfos);
                listenWordAnswerInfoWorkAnswers.setVersionId(listenWordAnswerInfo.getwId());
                if (listenWordAnswerInfo.isRight()) {
                    listenWordAnswerInfoWorkAnswers.setAssess(WorkAnswers.Assess.ASSESS_CORRECT);
                } else {
                    listenWordAnswerInfoWorkAnswers.setAssess(WorkAnswers.Assess.ASSESS_ERROR);
                }

                mSubmitAnswers.add(listenWordAnswerInfoWorkAnswers);
            }

            // 生成userAnswer.json
            Gson gson = new Gson();
            String userAnswerJson = gson.toJson(mSubmitAnswers, new TypeToken<List<WorkAnswers<DictationAnswerInfo>>>() {
            }.getType());

            if (!TextUtils.isEmpty(userAnswerJson)) {
                mAnswer.setWorkAnswers(userAnswerJson);
            } else {
                //用户答案为空
            }

            if (null != mWorkContents) {
                //如果是作业使用作业接口里面数据的不使用资源里面的
                mAnswer.setVersionId(mWorkContents.getVersionId());
                mAnswer.setParentVersionId(mWorkContents.getParentVersionId());
            }

            mAnswer.setStartTime(startTime);
            String json = mAnswer.toString();
            try {
                JSONObject jsonObject = new JSONObject(json);
                String key = "workAnswers";
                if (jsonObject.has(key)) {
                    JSONArray array = new JSONArray(mAnswer.getWorkAnswers());
                    jsonObject.remove(key);
                    jsonObject.put(key, array);
                    json = jsonObject.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            final String finalJson = json;
            EpaperDao.getInstance().submitReadWork(json, 0, mAnswer.getWorkId(), mAnswer.getContentId(), new BaseExtCallBack(DictationRedoAndResultActivity.this, getUserInfoBase().getUserId() + "") {
                @Override
                public void success(Object data) {//try

                    SubmitResult submitResult = (SubmitResult) data;
                    mDoWorkId = submitResult.getDoWorkId();//返回DOWORKid
                    returnWorkLong = submitResult.getWorkLong();
                    Log.d(TAG, "#######提交作业 success#########");
                    if (mHandler.hasMessages(ANSWER_SUBMIT)) {
                        mHandler.removeMessages(ANSWER_SUBMIT);
                    }
                    commitSuccess();
                }

                @Override
                public void failed(final Object data) {

                    if (null != data) {
                        Log.d(TAG, "#######提交作业 failed#########" + data.toString());
                        FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_DICTATION, data.toString(), finalJson, "报听写提交作业失败：" + getUrl());
                    }
                    try {
                        mIsHasSubmited = false;
                        netSpeedTask.cancel();//取消定时任务
                        result_contail.setVisibility(View.GONE);
                        submiting.setVisibility(View.GONE);
                        submit_fail.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.getStackTrace();
                    }

                }

                @Override
                public void failed(final int errorCode, final Object data) {
                    try {
                        setUpload(false);
                        super.failed(errorCode, data);
                        if (errorCode == 105) {
                            commitSuccess();
                        } else {
                            if (null != data) {
                                Log.d(TAG, "#######提交作业 failederrorCode #########" + data.toString());
                                FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_DICTATION, data.toString(), finalJson, "报听写提交作业失败：" + getUrl());
                            }

                            if (errorCode != EConstants.ERROR_CODE_REPEAT_COMMIT) {
                                mIsHasSubmited = false;
                                netSpeedTask.cancel();//取消定时任务
                                result_contail.setVisibility(View.GONE);
                                submiting.setVisibility(View.GONE);
                                submit_fail.setVisibility(View.VISIBLE);
                            } else {
                                commitSuccess();
                            }
                        }


                    } catch (Exception e) {
                        e.getStackTrace();
                    }

                }
            });

        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    private void commitSuccess() {


        try {
            //清除做作业记录  相关缓存

            clearRecord();
            saveDoWorkRecord(null);
            //提交作业成功 清除作业开始时间
            CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, mPosition, mWorkId), 0);

            FileUtils.delete(ESystem.getAnswersUuidPath(mUuid));
            CWSys.setSharedInt(getSaveTime(), 0);
            result_contail.setVisibility(View.GONE);
            submiting.setVisibility(View.GONE);
            submit_fail.setVisibility(View.GONE);
            //结果页面
            submit_result_lay.setVisibility(View.VISIBLE);
            updateUiSussess();//显示结果页面
            saveSubmitState(false);//提交过作业
            mIsSubmited = true;//提交成功
            mIsHasSubmited = false;
            sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
            sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
        } catch (Exception e) {
            e.getStackTrace();
        }


        try {

            //作业过来的
            if (Long.valueOf(mWorkId) > 0 && mWorkContents != null) {
                score_result_page.setRankLinIsVis(View.VISIBLE);
                score_result_page.setOnToRankListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MeJumpManager.jumpToRankH5Activity(R.string.go_back, DictationRedoAndResultActivity.this, mWorkContents.getContentId() + "", mWorkContents.getResourceName());
                    }
                });
            } else {
                //自主学习
                score_result_page.setRankLinIsVis(View.GONE);
            }

        } catch (Exception e) {
            score_result_page.setRankLinIsVis(View.GONE);
            e.printStackTrace();
        }

    }


    //检测网速任务
    TimerTask netSpeedTask = new TimerTask() {
        @Override
        public void run() {

            if (!mIsSubmited && !isFinishing()) {
                showNetSpeed();
            } else {
                //提交成功后就不需要展示网络状况
                cancel();
            }

        }
    };

    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;

    private void showNetSpeed() {

        long nowTotalRxBytes = getTotalRxBytes();
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
        if (speed < 3) {
            Random rand = new Random();
            speed = rand.nextInt(3);
        }

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        Message msg = mHandler.obtainMessage();
        msg.what = MSG_NET_SPEED;
        msg.obj = (int) speed;
        mHandler.sendMessage(msg);//更新界面
    }

    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }


    public void updateUiSussess() {//更新结果页UI
        score_result_page.setDispayType(SubmitSuccessfulResultPage.DISPLAY_TYPE_DICTATION);

        //先设置总分
        if (null != mWorkContents && mWorkContents.getWorkScore() > 0) {
            mTotalScore = mWorkContents.getWorkScore();
            nowTime = mWorkContents.getNowDate();
            // 查看类型：0 提交立马能查看，1截止时间到后查看
            ShowScoreMode = mWorkContents.getShowScoreMode();
        }
        score_result_page.setToalScore(mTotalScore);
        score_result_page.setEvaluateState(0, true, mActualScore + "", -1, nowTime, effectiveDate, ShowScoreMode, serviceExpired);
        score_result_page.setTitleText(mTitleText);
        //如果返回作业用时失败 则使用旧用时
        if (returnWorkLong != 0) {
            score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, (int) returnWorkLong));
        } else {
            score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, mWorkLong));
        }

        hideTitleBar();
        btn_return_last_page.setText("完成");
    }

    private void showDailog() {
        CWDialog mDialog = new CWDialog(this);
        // mDialog.setTitle(R.string.lear_title);
        mDialog.setMessage(R.string.confirm_back_work);
        mDialog.setPositiveButton(android.R.string.cancel, null);
        mDialog.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                finish();

            }
        });
        mDialog.show();
    }

    /**
     * 退出提示框
     */
    private void showConfirmEndDialog() {
        if (isDestroy) {
            return;
        }
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.confirm_no_submit_work);
        dialog.setCancelable(true);
        dialog.setPositiveButton(android.R.string.cancel, null).setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                finish();

            }
        }).show();
    }

    //得到加密后的URL
    public String getShareBase64Url() {
        String shareUrl;
        StringBuffer sb1 = new StringBuffer(EpaperConstant.URL_H5_DICATION);
        StringBuffer sb = new StringBuffer();
        sb.append("pageType=2");
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long useeId = getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(useeId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&versionId=");
        sb.append("0".equals(mVersionId) ? mParentVersionId : mVersionId);
        sb.append("&parentVersionId=");
        sb.append(mParentVersionId);
        sb.append("&doWorkId=");
        sb.append(mDoWorkId);
        String title;
        try {
            title = java.net.URLEncoder.encode(mTitleText, "UTF-8");

        } catch (Exception e) {
            title = "";
        }
        sb.append("&title=");
        sb.append(title);
        String param = Base64Utils.getBase64(sb.toString());
        shareUrl = sb1.append(param).toString();
        return shareUrl;
    }


    /**
     * 保存答案记录和UUID记录
     *
     * @param listenWordAnswers
     */
    protected void saveDoWorkRecord(ArrayList<DictationAnswerInfo> listenWordAnswers) {
        String key = RepeatKeyUtil.getWordRepeatAnswerListKey(mDownLoadInfo, mModule, mPosition, mWorkId, mUuid);
        SerializableManager.getInstance().serialize(key, listenWordAnswers);
    }

    /**
     * 获取作业用时
     *
     * @return
     */
    protected String getSaveTime() {
        String key = ESystem.getSaveRecordKeywithMode(mDownLoadInfo, mModule, mPosition, mWorkId, SerializableManager.SerializeKey.SHARE_KEY_DO_WORK_TIME, 0);
        return key + "_" + getUserInfoBase().getUserId();
    }

    /**
     * 获取提交状态的key
     *
     * @return
     */
    protected String getSubmitStateKey() {
        String key = ESystem.getSaveRecordKeywithModeandUUid(mDownLoadInfo, mModule, mPosition, mWorkId, SerializableManager.SerializeKey.SUBMIT_STATE, 0, mUuid);
        return key + "_" + getUserInfoBase().getUserId();
    }

    /**
     * 保存答案记录和UUID记录
     *
     * @param
     */
    protected void saveSubmitState(boolean submit) {
        CWSys.setSharedBoolean(getSubmitStateKey(), submit);
    }

    /**
     * 清除记录
     */
    private void clearRecord() {
        CWSys.setSharedString(RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo, mModule, mPosition, mWorkId, 0), null);
        FileUtils.delete(ESystem.getAnswersUuidPath(RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo, mModule, mPosition, mWorkId, 0)));
    }

    /**
     * 获取平均分
     *
     * @return
     */
    public double getAvgScore() {
        if (mListenWordAnswerInfos != null && mListenWordAnswerInfos.size() > 0) {
            int right = 0;
            for (DictationAnswerInfo listenWordAnswerInfo : mListenWordAnswerInfos) {
                if (listenWordAnswerInfo.isRight()) {
                    right++;
                }
            }
            if (right > 0) {
                BigDecimal bg3 = new BigDecimal(right * 100.00 / mListenWordAnswerInfos.size());
                double f3 = bg3.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                return f3;
            } else {
                return 0;
            }
        }
        return 0;
    }

    @Override
    public void redoWord(int position) {
        EpaperJumpManager.jumpToDictaionFromRedo(R.string.go_back, DictationRedoAndResultActivity.this, mWordDetailList.get(position), mDownLoadInfo, true, RequestCode.RereadWordResultActivityResquestCode.REPEATE_WORD_REQUEST, mTitleText, mListenWordAnswerInfos.get(position));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        WxShareHelper.getInstance().release();
        QQShareHelper.getInstance().release();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            try {
                if (requestCode == RequestCode.RereadWordResultActivityResquestCode.REPEATE_WORD_REQUEST) {
                    if (data == null) {
                        return;
                    }

                    DictationAnswerInfo listenWordAnswerInfo = (DictationAnswerInfo) data.getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);
                    int repeatWorkTime = data.getIntExtra(IntentFlag.INTENT_FLAG_WORK_TIME, 0);

                    if (listenWordAnswerInfo != null && mListenWordAnswerInfos != null && mListenWordAnswerInfos.size() > 0) {
                        Iterator<DictationAnswerInfo> iterator = mListenWordAnswerInfos.iterator();
                        while (iterator.hasNext()) {
                            DictationAnswerInfo next = iterator.next();
                            if (next.getwId().equals(listenWordAnswerInfo.getwId())) {
                                next.setWordAnswer(listenWordAnswerInfo.getWordAnswer());
                                next.setRight(listenWordAnswerInfo.isRight());
                                next.setPretations(listenWordAnswerInfo.getPretations());
                            }
                        }
                        mDictationRedoAdapter.notifyDataSetInvalidated();
                        mWorkLong = mWorkLong + repeatWorkTime;
                        saveDoWorkRecord(mListenWordAnswerInfos);
                        CWSys.setSharedInt(getSaveTime(), mWorkLong);
                    }


                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        }

    }
}